import platform
import os
import subprocess
import sys
import distro

apps_in_os = dict()
apps_in_os['windows'] = {'git','pip','vim','ssh','input_method'}
apps_in_os['linux'] = {'git', 'pip', 'vim'}
# apps_in_os['ubuntu'] = apps_in_os['linux'].union({'apt',})
# apps_in_os['centos'] = apps_in_os['linux'].union({'yum',})
apps_in_os['debian'] = apps_in_os['ubuntu']
apps_in_os['darwin'] = apps_in_os['linux']

import logging
logging.basicConfig(level=logging.DEBUG)

python = sys.executable
dirpath = os.path.abspath('.')
system = platform.system()
if system == 'Linux':
    system = distro.id().lower()
elif system == 'Windows':
    system = 'windows'
elif system == "Darwin":
    system = 'darwin'
logging.debug("system={}".format(system))
apps = apps_in_os[system]

def install_one(app):
    global dirpath, apps
    global system
    if app not in apps:
        logging.info("Cannot install {} on {}".format(app, system))
        return None
    path = os.path.join(dirpath, app)
    os.chdir(path)
    if os.path.exists("./install.py"):
        pcmd = [python, "./install.py"]
        p = subprocess.Popen(pcmd, stdout=subprocess.PIPE)
        p.wait()
    else:
        if system == 'windows':
            p = subprocess.Popen(r"cmd.exe /c .\install.bat", stdout = subprocess.PIPE)
            p.wait()
        elif system in ['ubuntu', 'centos']:
            p = subprocess.Popen(["bash", "./install.sh"], stdout=subprocess.PIPE)
            p.wait()
    print("Successfully install {} on {}".format(app, system))

def install_all():
    global apps, system
    for app in apps:
        install_one(app)

if __name__ == '__main__':
    apps_to_install = sys.argv[1:]
    if apps_to_install == []:
        install_all()
    else:
        for app in apps_to_install:
            install_one(app)
